package com.lmf.mock.starter.autoconfigure.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lmf.mock.starter.autoconfigure.entity.MockApi;
import com.lmf.mock.starter.autoconfigure.entity.MockGroup;
import com.lmf.mock.starter.autoconfigure.mapper.MockGroupMapper;
import com.lmf.mock.starter.autoconfigure.service.MockApiService;
import com.lmf.mock.starter.autoconfigure.service.MockGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Mock分组服务实现类
 */
@Service
public class MockGroupServiceImpl extends ServiceImpl<MockGroupMapper, MockGroup> implements MockGroupService {

    @Autowired
    private MockApiService mockApiService;

    @Override
    public List<MockGroup> getEnabledGroups() {
        QueryWrapper<MockGroup> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("enabled", true)
                   .orderByAsc("sort_order", "id");
        return list(queryWrapper);
    }

    @Override
    public MockGroup getGroupById(Long id) {
        return getById(id);
    }

    @Override
    public boolean createGroup(MockGroup group) {
        if (group.getSortOrder() == null) {
            group.setSortOrder(0);
        }
        if (group.getEnabled() == null) {
            group.setEnabled(true);
        }
        return save(group);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateGroup(MockGroup group) {
        // 获取原分组信息
        MockGroup oldGroup = getById(group.getId());
        if (oldGroup == null) {
            return false;
        }
        
        // 更新分组
        boolean updateResult = updateById(group);
        
        // 如果分组状态发生变化，同步更新其下所有接口的状态
        if (updateResult && group.getEnabled() != null && !group.getEnabled().equals(oldGroup.getEnabled())) {
            UpdateWrapper<MockApi> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("group_id", group.getId())
                        .set("enabled", group.getEnabled());
            mockApiService.update(updateWrapper);
        }
        
        return updateResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteGroup(Long id) {
        // 先删除该分组下的所有接口
        QueryWrapper<MockApi> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("group_id", id);
        mockApiService.remove(queryWrapper);
        
        // 再删除分组
        return removeById(id);
    }
}
